﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BLL;
using System.IO;

public partial class TotalPlan_SendTotalPlan : System.Web.UI.Page
{
    Authentication dllAuthentication = new Authentication();
    protected void Page_Load(object sender, EventArgs e)
    {
        dllAuthentication.isLogin();
        if (!IsPostBack)
        {
            bindDropDownList(this.drpDepartment);
            bindDropDownList(this.drpYear);
            bindGridView();
        }
        if (Request.Params["Year"] != null && Request.Params["Year"].ToString().Length != 0 && Request.Params["department"] != null && Request.Params["department"].ToString().Length != 0)
        {
            string Year = Request.Params["Year"].ToString();
            this.drpYear.SelectedValue = Year;
            string department = Request.Params["department"].ToString();
            this.drpDepartment.SelectedValue = department;
            bindGridView();
        }
    }

    void bindGridView()
    {
        object[] _value = new object[2];
        _value[0] = this.drpYear.SelectedItem.Text;
        _value[1] = this.drpDepartment.SelectedItem.Text;
        TotalPlanMgr dllTotalPlanMgr = new TotalPlanMgr();
        //根据年份获得总表计划
        DataTable dt = dllTotalPlanMgr.getTotalPlanSendByYearAndDepartment(_value);
        this.gdvTotalPlan.DataSource = dt;
        this.gdvTotalPlan.DataBind();
        for (int i = 0; i < this.gdvTotalPlan.Rows.Count; i++)
        {
            if (this.gdvTotalPlan.DataKeys[i]["AttachmentPath"].ToString().Length == 0)
            {
                Button _btn = (Button)this.gdvTotalPlan.Rows[i].Cells[12].FindControl("btnDownLoad");
                _btn.Visible = false;
                Label _lbl = (Label)this.gdvTotalPlan.Rows[i].Cells[12].FindControl("lblAlert");
                _lbl.Visible = true;
                _lbl.Text = "无附件";
            }
        }
    }




    /// <summary>
    /// 绑定下拉列表
    /// </summary>
    /// <param name="_drp"></param>
    void bindDropDownList(DropDownList _drp)
    {
        if (_drp.Equals(this.drpYear))
        {
            for (int i = 2009; i < 2100; i++)
            {
                ListItem li = new ListItem(i.ToString(), i.ToString());
                _drp.Items.Add(li);
            }
            //根据系统日期自动绑定到当前年份
            string _year = DateTime.Now.Year.ToString();
            this.drpYear.SelectedIndex = this.drpYear.Items.IndexOf(this.drpYear.Items.FindByText(_year));
        }
        if (_drp.Equals(this.drpDepartment))
        {
            Model.UserInfo objUserInfo = new Model.UserInfo();
            if (objUserInfo.UserName == "admin")
            {
                DepartmentInfoManager dllDepartmentInfoManager = new DepartmentInfoManager();
                DataTable dt = dllDepartmentInfoManager.getNoTree();
                this.drpDepartment.DataSource = dt;
                this.drpDepartment.DataTextField = "DepartmentName";
                this.drpDepartment.DataValueField = "DepartmentId";
                this.drpDepartment.DataBind();
            }
            else
            {
                UserInfoManager dllUserInfoManager = new UserInfoManager();
                object[] _department = new object[1];                
                _department[0] = objUserInfo.UserName;
                DataTable _userTable = dllUserInfoManager.get(UserInfoManager.field.UserName.ToString(), _department);
                if (_userTable.Rows.Count > 0)
                {
                    if (_userTable.Rows[0]["DepartmentId"].ToString().Length > 0)
                    {
                        ListItem _li = new ListItem(_userTable.Rows[0]["DepartmentId"].ToString());
                        this.drpDepartment.Items.Add(_li);
                    }
                    if (_userTable.Rows[0]["PartTimeDepartmentId"].ToString().Length > 0)
                    {
                        ListItem _li = new ListItem(_userTable.Rows[0]["PartTimeDepartmentId"].ToString());
                        this.drpDepartment.Items.Add(_li);
                    }
                }
            }
        }
    }


    /// <summary>
    /// 生成DataTable
    /// </summary>
    /// <returns>DataTable</returns>
    DataTable genDataTable()
    {
        DataTable dt = new DataTable();
        DataColumn dc = new DataColumn("TotalPlanId");
        dt.Columns.Add(dc);
        dc = new DataColumn("TotalPlanSortId");
        dt.Columns.Add(dc);
        dc = new DataColumn("CompleteTime");
        dt.Columns.Add(dc);
        dc = new DataColumn("Source");
        dt.Columns.Add(dc);
        dc = new DataColumn("WorkItem");
        dt.Columns.Add(dc);
        dc = new DataColumn("MasterPeople");
        dt.Columns.Add(dc);
        dc = new DataColumn("TotalYear");
        dt.Columns.Add(dc);
        dc = new DataColumn("PlanSendState");
        dt.Columns.Add(dc);
        dc = new DataColumn("Source");
        dt.Columns.Add(dc);
        dc = new DataColumn("VerifyCircuitId");
        dt.Columns.Add(dc);
        dc = new DataColumn("WorkItemAdditional");
        dt.Columns.Add(dc);
        return dt;
    }

    /// <summary>
    /// 将GridView内容导入DataTable
    /// </summary>
    /// <returns></returns>
    DataTable GridViewToDataTable(GridView _gdv, DataTable _dt)
    {
        //获取当前GridView内容导入DataTable
        for (int i = 0; i < _gdv.Rows.Count; i++)
        {
            DataRow dr = _dt.NewRow();
            //总表计划id
            dr["TotalPlanId"] = _gdv.DataKeys[i]["TotalPlanId"].ToString();
            //总表计划排序id
            dr["TotalPlanSortId"] = _gdv.Rows[i].Cells[1].Text;
            //完成时间
            dr["CompleteTime"] = _gdv.Rows[i].Cells[3].Text;
            //总表计划内容
            dr["WorkItem"] = _gdv.Rows[i].Cells[2].Text;
            //来源
            dr["Source"] = _gdv.DataKeys[i]["Source"].ToString();
            //负责人
            dr["MasterPeople"] = _gdv.Rows[i].Cells[4].Text;
            //总表计划年份
            dr["TotalYear"] = this.drpYear.SelectedItem.Text;
            dr["VerifyCircuitId"] = _gdv.DataKeys[i]["VerifyCircuitId"].ToString();
            dr["PlanSendState"] = _gdv.DataKeys[i]["PlanSendState"].ToString();
            dr["Source"] = _gdv.DataKeys[i]["Source"].ToString();
            dr["WorkItemAdditional"] = _gdv.DataKeys[i]["WorkItemAdditional"].ToString();
            _dt.Rows.Add(dr);
        }
        return _dt;
    }


    /// <summary>
    /// 年份改变事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void drpYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindGridView();
    }


    /// <summary>
    /// 全选事件 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ckbAllSelect_CheckedChanged(object sender, EventArgs e)
    {
        if (this.ckbAllSelect.Checked == true)
        {
            for (int i = 0; i < this.gdvTotalPlan.Rows.Count; i++)
            {
                CheckBox _chk = ((CheckBox)this.gdvTotalPlan.Rows[i].Cells[0].FindControl("ckbSelect"));
                _chk.Checked = true;
            }
        }
        else
        {
            for (int i = 0; i < this.gdvTotalPlan.Rows.Count; i++)
            {
                CheckBox _chk = ((CheckBox)this.gdvTotalPlan.Rows[i].Cells[0].FindControl("ckbSelect"));
                _chk.Checked = false;
            }
        }
    }

    /// <summary>
    /// GridView行处理事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gdvTotalPlan_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            e.Row.Cells[2].Text = e.Row.Cells[2].Text.Replace("&nbsp;", "");
            e.Row.Cells[12].Text = e.Row.Cells[12].Text.Replace("&nbsp;", "");
            e.Row.Cells[2].Text += e.Row.Cells[12].Text;
            e.Row.Cells[12].Visible = false;
        }
    }

    /// <summary>
    /// 下载事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDownLoad_Click(object sender, EventArgs e)
    {
        int i = 0;
        Button btt = (Button)sender;//获得当前控件
        TableCell cell = (TableCell)btt.Parent;//得到所处的父单元格
        GridViewRow iRow = (GridViewRow)cell.Parent;//得到所处父单元行
        i = iRow.RowIndex;//得到该行的索引
        //读取隐藏地址列
        string path = this.gdvTotalPlan.DataKeys[i]["AttachmentPath"].ToString();
        FileDownload(path); 
    }

    /// <summary>
    /// 上传事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnAttachmentPath_Click(object sender, EventArgs e)
    {
        string _totalPlanId = "";
        int _count = 0;
        for (int i = 0; i < this.gdvTotalPlan.Rows.Count; i++)
        {
            CheckBox ckb = (CheckBox)this.gdvTotalPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (ckb.Checked == true)
            {
                _totalPlanId = this.gdvTotalPlan.DataKeys[i]["TotalPlanId"].ToString();
                _count++;
            }
        }
        if (_count == 1)
        {
            string department = Server.UrlEncode(this.drpDepartment.SelectedItem.Text);
            //定向到添加年附件路径页面
            string _url = "../WebCommon/AttachmentPath.aspx?PlanId=" + _totalPlanId + "&PlanType=11" + "&department=" + department + "&Year=" + this.drpYear.SelectedItem.Text;
            Page.RegisterStartupScript("windowsopen", "<script language=javascript>window.open('" + _url + "','quarterplandetailmodify','height=40,width=400,top=300,left=300,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');</script>");
        }
        if (_count > 1)
        {
            Utility.HttpHelp.alert("只能选择一个计划", Page);
            return;
        }
        if (_count == 0)
        {
            Utility.HttpHelp.alert("请选择一个计划", Page);
            return;
        }
    }


    ///   <summary>   
    ///   文件下载   
    ///   </summary>   
    ///   <param   name="FullFileName"></param>   
    private void FileDownload(string strFileName)
    {
        FileInfo DownloadFile = new FileInfo(strFileName);
        if (!DownloadFile.Exists)
        {
            Utility.HttpHelp.alert("无附件,请与管理员联系", Page);
            return;
        }
        Response.Clear();
        Response.ClearHeaders();
        Response.Buffer = false;
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName.Substring(strFileName.LastIndexOf('\\') + 1), System.Text.Encoding.UTF8));
        // Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());

        Response.WriteFile(DownloadFile.FullName);
        Response.Flush();
        Response.End();

    }


    /// <summary>
    /// 流程查看事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnVerifyCircuit_Click(object sender, EventArgs e)
    {
        int _count = 0;
        string _url = "";
        int _totalPlanId = 0;
        for (int i = 0; i < this.gdvTotalPlan.Rows.Count; i++)
        {
            CheckBox ckb = (CheckBox)this.gdvTotalPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (ckb.Checked == true)
            {
                _count++;
                _totalPlanId = Convert.ToInt32(this.gdvTotalPlan.DataKeys[i]["TotalPlanId"].ToString());
            }
        }
        if (_count > 1)
        {
            Utility.HttpHelp.alert("只能选择一个计划", Page);
            return;
        }
        if (_count == 0)
        {
            Utility.HttpHelp.alert("请选择一个计划", Page);
            return;
        }
        _url = "../WebCommon/VerifyCircrtForTotalPlan.aspx?PlanId=" + _totalPlanId + "&PlanType=4";
        Page.RegisterStartupScript("windowOpen",
           "<script language=javascript>window.open('" + _url + "','newwindow','height=150,width=550,top=250,left=300,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');</script>");
    }


    /// <summary>
    /// 撤销事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        int _count = 0;
        List<object[]> _valueList = new List<object[]>();
        string _alert = "";
        for (int i = 0; i < this.gdvTotalPlan.Rows.Count; i++)
        {
            CheckBox ckb = (CheckBox)this.gdvTotalPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (ckb.Checked == true)
            {
                _count++;
                //根据总表计划id，查询计划在流程审核的位置
                object[] _value = new object[1];
                _value[0] = Convert.ToInt32(this.gdvTotalPlan.DataKeys[i]["TotalPlanId"].ToString());
                int state = Convert.ToInt32(this.gdvTotalPlan.DataKeys[i]["PlanSendState"].ToString());

                if (state < 3)
                {
                    _valueList.Add(_value);
                }
                else
                {
                    _alert += this.gdvTotalPlan.DataKeys[i]["TotalPlanId"].ToString() + ",";
                }
            }
        }
        if (_count == 0)
        {
            Utility.HttpHelp.alert("请至少选择一个计划", Page);
            return;
        }
        if (_valueList.Count > 0)
        {
            TotalPlanMgr dllTotalPlanMgr = new TotalPlanMgr();
            int result = dllTotalPlanMgr.RollBackTotalPlan(_valueList);
            if (result == 0)
            {
                Utility.Error.RedirectErrorPage("撤回总表计划未成功，请重试！");
            }
            else
            {
                bindGridView();
            }
        }
        if (_alert.Length > 0)
        {
            Utility.HttpHelp.alert("计划编号为" + _alert + "的计划的总表计划已经审核完毕不可撤回", Page);
        }
        if (this.ckbAllSelect.Checked)
        {
            this.ckbAllSelect.Checked = false;
        }
    }
    protected void drpDepartment_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindGridView();
    }
}
